package router

import (
	"crow-qin/app/config"
	"crow-qin/app/models"
	"crow-qin/app/pkg"
	"crow-qin/app/service"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/toolkits/pkg/logger"
)

type rAdmin struct {
	//service.SysUser
	//userList []service.SysUser
}

// auth
// 认证管理员用户
func (a *rAdmin) auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从token判断
		var j service.JWTClaims
		idAuth, myName, err := j.Verify(c)
		if err != nil {
			SetErrDefault(c, err)
			return
		}
		if idAuth == false {
			err = errors.New("身份认证失败")
			SetErrDefault(c, err)
			return
		}
		myRole, err := models.GetRoleByUserName(myName, config.MyTx)
		logger.Info(myRole)
		if myRole != "admin" {
			err = errors.New("没有管理员权限")
			SetErrDefault(c, err)
			return
		}
		c.Next()
	}
}

// CreateUser 创建用户
// @Summary 创建用户
// @Description 创建用户
// @Tags admin
// @Accept  application/json
// @Product application/json
// @Param data body []CreateUsersRequest  true "填写用户信息"
// @Success 200 {object} response.Response{data=CreateUsersResponse} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/admin/user [post]
// @Security Bearer
func (a *rAdmin) CreateUser(c *gin.Context) {
	var createUsersRequest []CreateUsersRequest
	err := c.Bind(&createUsersRequest)
	if err != nil {
		SetErrDefault(c, err)
		return
	}

	//输入检查
	for _, srcUser := range createUsersRequest {
		if srcUser.UserName == "" {
			err = errors.New("用户名不能为空")
			SetErrDefault(c, err)
			return
		}
		if srcUser.Role == "" {
			err = errors.New("用户角色不能为空")
			SetErrDefault(c, err)
			return
		}
		err = pkg.CheckPassword(srcUser.Password)
		if err != nil {
			SetErrDefault(c, err)
			return
		}
	}

	sysAdmin := &service.SysAdmin{}

	//组装admin的userList
	for _, srcUser := range createUsersRequest {
		u := service.CreateUser(srcUser.UserName, srcUser.Password, srcUser.Email, srcUser.Phone, srcUser.Role)
		sysAdmin.AddUser(*u)
	}

	//定义返回的实例
	var response CreateUsersResponse
	//创建系统用户，获取返回值
	response.SuccessfulList, response.FailedList, err = sysAdmin.CreateUsers()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, response)
}

type CreateUsersRequest struct {
	UserName string `json:"user_name"`
	Password string `json:"password"`
	Email    string `json:"email"`
	Phone    string `json:"phone"`
	Role     string `json:"role"`
}

type CreateUsersResponse struct {
	SuccessfulList []string
	FailedList     []string
}

// DeleteUser 删除指定用户
// @Summary 删除指定用户
// @Description 删除指定用户
// @Tags admin
// @Param uuid path string true "用户id"
// @Success 200 {object} response.Response{data=string} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/admin/user/{uuid} [delete]
// @Security Bearer
func (a *rAdmin) DeleteUser(c *gin.Context) {
	uuid := c.Param("uuid")
	userId := service.StringToInt64(uuid)

	//检查用户是否存在
	var dUser service.SysUser
	dUser.ID = userId
	err := dUser.DeleteUser()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, "删除成功")
}

// ResetUserPassword 批量重置用户密码
// @Summary 批量重置用户密码
// @Description 批量重置用户密码
// @Tags admin
// @Accept  application/json
// @Product application/json
// @Param data body []ResetUserPasswordRequest  true "填写用户Id和xin密码"
// @Success 200 {object} response.Response{data=ResetUsersPasswordResponse} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/admin/user/list/password [put]
// @Security Bearer
func (a *rAdmin) ResetUserPassword(c *gin.Context) {
	var request []ResetUserPasswordRequest
	err := c.Bind(&request)
	if err != nil {
		SetErrDefault(c, err)
		return
	}

	//输入检查
	for _, srcUser := range request {
		if srcUser.UserId == 0 {
			err = errors.New("用户id不能为空")
			SetErrDefault(c, err)
			return
		}
		err = pkg.CheckPassword(srcUser.NewPassword)
		if err != nil {
			SetErrDefault(c, err)
			return
		}
	}

	//修改密码
	sysAdmin := &service.SysAdmin{}
	//组装admin的userList
	for _, srcUser := range request {
		var u service.SysUser
		u.ID = srcUser.UserId
		u.Password = pkg.EncryptWithMd5(srcUser.NewPassword)
		sysAdmin.AddUser(u)
	}

	//定义返回的实例
	var response ResetUsersPasswordResponse
	//创建系统用户，获取返回值
	response.SuccessfulList, response.FailedList, err = sysAdmin.UpdateUsers()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, response)
}

type ResetUserPasswordRequest struct {
	UserId      int64  `json:"user_id"`
	NewPassword string `json:"new_password"`
}

type ResetUsersPasswordResponse struct {
	SuccessfulList []string
	FailedList     []string
}

// UpdateUsersInfo 修改用户信息
// @Summary 修改用户信息
// @Description 修改用户信息
// @Tags admin
// @Accept  application/json
// @Product application/json
// @Param data body UpdateUsersInfoRequest  true "user_id必须，其他可选"
// @Success 200 {object} response.Response{data=string} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/admin/user [put]
// @Security Bearer
func (a *rAdmin) UpdateUsersInfo(c *gin.Context) {
	var request UpdateUsersInfoRequest
	err := c.Bind(&request)
	if err != nil {
		SetErrDefault(c, err)
		return
	}

	//实例化service.SysUser
	var uu service.SysUser
	uu.ID = request.UserId
	uu.Email = request.Email
	uu.Phone = request.Phone
	//更新用户信息
	err = uu.Update()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, "用户信息修改成功")
}

type UpdateUsersInfoRequest struct {
	UserId int64  `json:"user_id"`
	Phone  string `json:"phone"`
	Email  string `json:"email"`
}

// GetUserList 获取用户信息
// @Summary 获取用户信息
// @Description 获取用户信息
// @Tags admin
// @Param role query string false "用户角色"
// @Param user_name query string false "用户名（可模糊查询）"
// @Param page_num query string false "页数"
// @Param page_size query string false "每页行数"
// @Success 200 {object} response.Response{data=GetUserListResponse} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/admin/user/list [get]
// @Security Bearer
func (a *rAdmin) GetUserList(c *gin.Context) {

	var userCondition service.SysUser
	//传输的数据
	userCondition.Role = c.Query("role")
	userCondition.UserName = c.Query("user_name")

	pageNumString := c.Query("page_num")
	pageNum := service.StringToInt64(pageNumString)
	pageSizeString := c.Query("page_size")
	pageSize := service.StringToInt64(pageSizeString)

	//调用service.user的方法 分页查询
	sysUserList, count, err := userCondition.GetUserList(pageSize, pageNum)
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	//组装结果
	if pageSize != 0 && pageNum == 0 {
		pageNum = 1
	}
	getUsersResponse := GetUserListResponse{
		PageSize: pageSize,
		PageNum:  pageNum,
		Count:    count,
		SysUsers: sysUserList,
	}

	//返回
	SetOK(c, getUsersResponse)

}

type GetUserListResponse struct {
	PageNum  int64 `json:"page_num"`
	PageSize int64 `json:"page_size"`
	Count    int64 `json:"count"`
	SysUsers []service.SysUser
}

// GetUser 获取指定用户信息
// @Summary 获取指定用户信息
// @Description 获取指定用户信息
// @Tags admin
// @Param uuid path string true "用户id"
// @Success 200 {object} response.Response{data=service.SysUser} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/admin/user/{uuid} [get]
// @Security Bearer
func (a *rAdmin) GetUser(c *gin.Context) {
	uuid := c.Param("uuid")
	userId := service.StringToInt64(uuid)
	//查询
	var sysUser service.SysUser
	sysUser.ID = userId
	err := sysUser.Get()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, sysUser)
}
